class CaseEditor {
    constructor() {
        this.globalConfig = this.initGlobalConfig();
        this.steps = [];
        this.currentStep = null;
        this.initDomEvents();
        this.adjustButtonPosition();
        this.debouncedSync = this.debounce((stepId) => this.syncFormToData(stepId), 500);
    }

    // 初始化全局配置
    initGlobalConfig() {
        return {
            name: 'HTTP用户登录接口',
            host: 'api.coolyuntest.com',
            port: 443,
            variables: '{"token": "{{ auth_token }}"}'
        };
    }

    // 防抖函数（带取消功能）
    debounce(fn, delay) {
        let timer;
        const wrapper = (...args) => {
            clearTimeout(timer);
            timer = setTimeout(() => fn(...args), delay);
        };
        wrapper.cancel = () => clearTimeout(timer);
        return wrapper;
    }

    // DOM事件初始化
    initDomEvents() {
        // 步骤列表操作
        $('#addStepBtn').on('click', () => this.handleAddStep());
        const stepList = $('#stepList');
        stepList.on('click', '.step-item', (e) => {
            if ($(e.target).hasClass('delete-step')) return;
            const stepId = $(e.currentTarget).data('id');
            this.selectStep(stepId);
        });
        stepList.on('click', '.delete-step', (e) => {
            e.stopPropagation();
            const stepId = $(e.currentTarget).closest('.step-item').data('id');
            this.deleteStep(stepId);
        });

        // 步骤编辑表单事件
        $('.step-name-input').on('input', () => this.triggerDebouncedSync());
        $('.api-url-input').on('input', () => this.triggerDebouncedSync());
        $('.protocol-select, .contentType-select').on('change', () => this.syncFormToDataImmediately());
        $('.editor-textarea').on('input', () => this.triggerDebouncedSync());
        $('#verifyCert').on('change', () => {
            this.syncFormToDataImmediately();
            $('.cert-path-group').toggle(this.isCertEnabled());
        });
        $('.cert-path-input').on('input', () => this.triggerDebouncedSync());

        // 全局配置事件
        $('#case-name, #case-host, #case-port, #global-variables').on('input', () => {
            this.syncGlobalConfig();
            this.persistData();
        });

        // 窗口调整事件
        $(window).on('resize', () => this.adjustButtonPosition());
    }

    // 触发防抖同步
    triggerDebouncedSync() {
        if (!this.currentStep) return;
        this.debouncedSync(this.currentStep.id);
    }

    // 立即同步表单数据
    syncFormToDataImmediately() {
        if (!this.currentStep) return;
        this.syncAllTabsData();
        this.persistData();
    }

    // 同步单个步骤数据
    syncFormToData(stepId) {
        const step = this.steps.find(s => s.id === stepId);
        if (!step) return;

        // 同步基础字段
        step.name = $('.step-name-input').val().trim();
        step.protocol = $('.protocol-select').val();

        // 同步协议配置
        const config = step.config;
        config.apiUrl = $('.api-url-input').val().trim();
        config.contentType = $('.contentType-select').val();
        config.sslEnabled = $('#verifyCert').prop('checked');
        config.sslCertPath = $('.cert-path-input').val().trim();

        // 同步当前选项卡数据
        config[this.getActiveTab()] = $(`#${this.getActiveTab()}`).val();

        this.persistData();
    }

    // 同步所有选项卡数据
    syncAllTabsData() {
        const step = this.currentStep;
        if (!step) return;

        ['variables', 'extract', 'export', 'validators', 'script'].forEach(tabId => {
            step.config[tabId] = $(`#${tabId}`).val();
        });
    }

    // 创建新步骤
    handleAddStep() {
        const newStep = {
            id: Date.now(),
            name: `步骤 ${this.steps.length + 1}`,
            protocol: 'HTTP',
            config: this.createStepConfig()
        };
        this.steps.push(newStep);
        this.renderStepList();
        this.selectStep(newStep.id);
    }

    // 初始化步骤配置
    createStepConfig() {
        return {
            apiUrl: '',
            contentType: 'application/json',
            sslEnabled: false,
            sslCertPath: '',
            variables: "{}",
            extract: "{}",
            export: "{}",
            validators: "[]",
            script: ""
        };
    }

    // 选择步骤
    selectStep(stepId) {
        this.debouncedSync.cancel();

        // 保存前一个步骤的修改
        if (this.currentStep) {
            this.syncAllTabsData();
            this.persistData();
        }

        const step = this.steps.find(s => s.id === stepId);
        if (!step) {
            this.currentStep = null;
            $('.step-editor-card').hide();
            return;
        }

        this.currentStep = step;
        $('.step-editor-card').show();
        this.updateEditorForm();
        this.highlightSelectedStep(stepId);
        this.scrollToStep(stepId);
    }

    // 更新编辑表单
    updateEditorForm() {
        if (!this.currentStep) return;

        const step = this.currentStep;
        $('.step-name-input').val(step.name);
        $('.protocol-select').val(step.protocol);
        $('.api-url-input').val(step.config.apiUrl);
        $('.contentType-select').val(step.config.contentType);
        $('#verifyCert').prop('checked', step.config.sslEnabled);
        $('.cert-path-input').val(step.config.sslCertPath);
        $('.cert-path-group').toggle(step.config.sslEnabled);

        // 更新所有选项卡内容
        ['variables', 'extract', 'export', 'validators', 'script'].forEach(tabId => {
            $(`#${tabId}`).val(step.config[tabId]);
        });
    }

    // 删除步骤
    deleteStep(stepId) {
        this.debouncedSync.cancel();
        const index = this.steps.findIndex(s => s.id === stepId);
        if (index === -1) return;

        this.steps.splice(index, 1);
        if (this.steps.length > 0) {
            const newIndex = Math.min(index, this.steps.length - 1);
            this.selectStep(this.steps[newIndex].id);
        } else {
            this.currentStep = null;
            $('.step-editor-card').hide();
        }
        this.renderStepList();
    }

    // 同步全局配置
    syncGlobalConfig() {
        this.globalConfig = {
            name: $('#case-name').val().trim(),
            host: $('#case-host').val().trim(),
            port: parseInt($('#case-port').val()) || 443,
            variables: $('#global-variables').val()
        };
    }

    // 持久化数据
    persistData() {
        console.log('Auto saved:', JSON.stringify({
            global: this.globalConfig,
            steps: this.steps.map(step => ({
                ...step,
                config: {...step.config} // 确保输出独立副本
            }))
        }));
    }

    // 获取当前激活的选项卡
    getActiveTab() {
        return $('.nav-link.active').attr('href').substring(1);
    }

    // 是否启用证书验证
    isCertEnabled() {
        return $('#verifyCert').prop('checked');
    }

    // 渲染步骤列表
    renderStepList() {
        const $container = $('#stepList').empty();
        this.steps.forEach(step => {
            const isActive = this.currentStep?.id === step.id;
            $container.append(`
                <div class="step-item${isActive ? ' active' : ''}" 
                     data-id="${step.id}">
                    <div class="d-flex justify-content-between align-items-center">
                        <span>${step.name}</span>
                        <i class="bi bi-trash delete-step"></i>
                    </div>
                    <small class="text-muted">${step.protocol}</small>
                </div>
            `);
        });
    }

    // 高亮选中步骤
    highlightSelectedStep(stepId) {
        $('.step-item').removeClass('active');
        $(`.step-item[data-id="${stepId}"]`).addClass('active');
    }

    // 滚动到指定步骤
    scrollToStep(stepId) {
        const $item = $(`.step-item[data-id="${stepId}"]`);
        if ($item.length) {
            const container = $('.step-items-container')[0];
            const itemTop = $item.offset().top;
            const containerTop = $(container).offset().top;
            container.scrollTo({
                top: itemTop - containerTop - 20,
                behavior: 'smooth'
            });
        }
    }

    // 调整按钮位置
    adjustButtonPosition() {
        const $btnGroup = $('.action-buttons-top');
        if ($(window).width() < 768) {
            $btnGroup.css({
                position: 'static',
                marginTop: '1rem'
            });
        } else {
            $btnGroup.css({
                position: 'absolute',
                top: '18px',
                right: '22px'
            });
        }
    }
}

// 初始化编辑器
$(document).ready(() => {
    window.caseEditor = new CaseEditor();
    $('a[data-bs-toggle="tab"]').on('shown.bs.tab', () => {
        window.caseEditor.syncFormToDataImmediately();
    });
});